package com.appspot.didit.client.tag;

import java.util.ArrayList;

import com.appspot.didit.client.util.Util;
import com.extjs.gxt.ui.client.event.*;
import com.extjs.gxt.ui.client.widget.MessageBox;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.*;
import com.google.gwt.event.logical.shared.*;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.*;
import com.google.gwt.user.datepicker.client.DateBox;

public class TagManageView extends Composite implements TagManagePresenter.View {

	public final Label shareHint;

	public final Label tagLabel;

	public final TextBox tagTb;

	public final Label userlistLabel;

	public final ListBox userlistLb;

	public final FlexTable userlistFt;

	public final Label beginLabel;

	public final DateBox beginDb;
	
	public final Label endLabel;

	public final DateBox endDb;
	
	public final Label costLabel;

	public final TextBox costTb;
	
	public final Label tagsLabel;

	public final TextBox tagsTb;
	
	public final Label combinedTagLabel;

	public final TextBox combinedTagTb;

	public final Button combineButton;
	
	public ArrayList<Button> delButton;
	
	public final Label inviteLabel;

	public final TextBox inviteTb;

	public final Button inviteButton;
	
	private final TagServiceAsync tagService = GWT.create(TagService.class);
	
	public TagManageView() {

		shareHint = new Label();
		delButton = new ArrayList<Button>();
		tagLabel = new Label("Projekt:");
		tagTb = new TextBox();
		tagTb.setReadOnly(true);
		tagTb.addFocusHandler(new FocusHandler() {
			public void onFocus(FocusEvent event) {
				TagCloud tc = TagManager.getInstance().getTagCloud();
				if (tc != null && !tc.isShowing()) {
					tc.show(tagTb);
				}
			}
		});
		tagTb.addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {
				tagTb.setStyleName("");
			}
		});
		
		tagTb.addValueChangeHandler(new ValueChangeHandler() {
			@Override
			public void onValueChange(ValueChangeEvent event) {
				update();
			}
		});
		tagTb.addKeyDownHandler(new KeyDownHandler() {
			@Override
			public void onKeyDown(KeyDownEvent event) {
				if (event.getNativeKeyCode() == KeyCodes.KEY_TAB) {
					 TagCloud tc = TagManager.getInstance().getTagCloud();
						if(tc != null && tc.getPartner().equals(tagTb)) {
							tc.hide();
						}
				 }
			}
        	
        });
		userlistLabel = new Label("Liste von Benutzern");
		userlistLb = new ListBox(true);
		userlistFt = new FlexTable();

		beginLabel = new Label("Projektbeginn:");
		beginDb = new DateBox();
		beginDb.setFormat(new DateBox.DefaultFormat(Util.completeDate));
		//beginDb.setValue(date);
		beginDb.addValueChangeHandler(new ValueChangeHandler() {
			@Override
			public void onValueChange(ValueChangeEvent event) {
				if(true) {
					Tag tag = TagManager.getInstance().myTagNameIndex.get(tagTb.getValue());
					tag.setProjectBegin(beginDb.getValue());
					tagService.update(tag, new AsyncCallback() {
		                public void onFailure(Throwable caught) {
		                    GWT.log("Failed to update a Tag", caught);
		                }
		                public void onSuccess(Object result) {
		                	GWT.log("sucessfully updated a Tag", null);
		                }		
		            });
				}
			}
		});
		
		endLabel = new Label("Projektende:");
		endDb = new DateBox();
		endDb.setFormat(new DateBox.DefaultFormat(Util.completeDate));
		//endDb.setValue(date);
		endDb.addValueChangeHandler(new ValueChangeHandler() {
			@Override
			public void onValueChange(ValueChangeEvent event) {
				//FIXME: condition 
				if(true) {
					Tag tag = TagManager.getInstance().myTagNameIndex.get(tagTb.getValue());
					tag.setProjectEnd(endDb.getValue());
					tagService.update(tag, new AsyncCallback() {
		                public void onFailure(Throwable caught) {
		                    GWT.log("Failed to update a Tag", caught);
		                }
		                public void onSuccess(Object result) {
		                	GWT.log("sucessfully updated a Tag", null);
		                }		
		            });
				}
			}
		});
		
		costLabel = new Label("Geschätzter Aufwand(in Stunden):");
		costTb = new TextBox();
		//costTb.setValue(value);
		costTb.addValueChangeHandler(new ValueChangeHandler() {
			@Override
			public void onValueChange(ValueChangeEvent event) {
				//FIXME: condition 
				if(true) {
					Tag tag = TagManager.getInstance().myTagNameIndex.get(tagTb.getValue());
					tag.setProjectCost(Double.parseDouble(costTb.getValue()));
					tagService.update(tag, new AsyncCallback() {
		                public void onFailure(Throwable caught) {
		                    GWT.log("Failed to update a Tag", caught);
		                }
		                public void onSuccess(Object result) {
		                	GWT.log("sucessfully updated a Tag", null);
		                }		
		            });
				}
			}
		});
		inviteLabel = new Label("Einzuladende Benutzer:");
		inviteTb = new TextBox();
		inviteButton = new Button("Einladen");
		disableDetails();
		tagsLabel = new Label("aktuelle Projekte:");
		tagsTb = new TextBox();
		tagsTb.setReadOnly(true);
		tagsTb.addFocusHandler(new FocusHandler() {
			public void onFocus(FocusEvent event) {
				TagCloud tc = TagManager.getInstance().getTagCloud();
				if (!tc.isShowing()) {
					tc.show(tagsTb);
				}
			}
		});
		tagsTb.addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {
				tagsTb.setStyleName("");
			}
		});
		tagsTb.addKeyDownHandler(new KeyDownHandler() {
			@Override
			public void onKeyDown(KeyDownEvent event) {
				if (event.getNativeKeyCode() == KeyCodes.KEY_TAB) {
					 TagCloud tc = TagManager.getInstance().getTagCloud();
						if(tc != null && tc.getPartner().equals(tagsTb)) {
							tc.hide();
						}
				 }
			}
        	
        });
		
		combinedTagLabel = new Label("Neues Projekt:");
		combinedTagTb = new TextBox();
		combinedTagTb.addFocusHandler(new FocusHandler() {
			public void onFocus(FocusEvent event) {
				TagCloud tc = TagManager.getInstance().getTagCloud();
				if (tc != null && !tc.isShowing()) {
					tc.show(tagsTb);
				}
			}
		});
		combinedTagTb.addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {
				tagsTb.setStyleName("");
			}
		});
		combineButton = new Button("Zusammenkleben");

		FlexTable layout = new FlexTable();
		layout.setCellSpacing(6);

		// Add some standard form options
		layout.setWidget(0, 0, shareHint);
		layout.setWidget(1, 0, tagLabel);
		layout.setWidget(1, 1, tagTb);
		layout.setWidget(2, 0, userlistLabel);
		layout.setWidget(2, 1, userlistFt);
		layout.setWidget(3, 0, beginLabel);
		layout.setWidget(3, 1, beginDb);
		layout.setWidget(4, 0, endLabel);
		layout.setWidget(4, 1, endDb);
		layout.setWidget(5, 0, costLabel);
		layout.setWidget(5, 1, costTb);
		layout.setWidget(6, 0, inviteLabel);
		layout.setWidget(6, 1, inviteTb);
		layout.setWidget(6, 2, inviteButton);
		layout.setWidget(7, 0, new HTML("<hr/>"));
		layout.setWidget(7, 1, new HTML("<hr/>"));
		layout.setWidget(7, 2, new HTML("<hr/>"));
		layout.setWidget(7, 3, new HTML("<hr/>"));
		layout.setWidget(7, 4, new HTML("<hr/>"));
		layout.setWidget(8, 0, new HTML("Projekte umbenennen / verbinden"));
		layout.setWidget(9, 0, tagsLabel);
		layout.setWidget(9, 1, tagsTb);
		layout.setWidget(9, 2, combinedTagLabel);
		layout.setWidget(9, 3, combinedTagTb);
		layout.setWidget(9, 4, combineButton);
		
		initWidget(layout);
	}

	public Widget getWidget() {
		return this;
	}

	public void reset() {

	}

	public HasClickHandlers getCombineClickHandlers() {
		return combineButton;
	}

	public HasText getShareHint() {
		return shareHint;
	}

	public HasValue<String> getTags() {
		return tagsTb;
	}
	
	public HasValue<String> getCombinedTag() {
		return combinedTagTb;
	}
	
	public HasValue<String> getUsername() {
		return null;
	}
	
	private void disableDetails() {
		beginDb.setValue(null);
		endDb.setValue(null);
		costTb.setValue("");
		beginDb.setEnabled(false);
		endDb.setEnabled(false);
		costTb.setEnabled(false);
		userlistFt.clear();
		inviteTb.setValue("");
		inviteTb.setEnabled(false);
		inviteButton.setEnabled(false);
	}
	
	public void update() {
		if (tagTb.getValue().contains(" ")) {
			tagTb.setValue(tagTb.getValue().substring(
					tagTb.getValue().lastIndexOf(" ") + 1));
		}
		if (!tagTb.getValue().equals("")) {
			final Tag t = TagManager.getInstance().myTagNameIndex.get(tagTb.getValue());
			beginDb.setEnabled(true);
			endDb.setEnabled(true);
			costTb.setEnabled(true);
			beginDb.setValue(t.getProjectBegin());
			endDb.setValue(t.getProjectEnd());
			costTb.setValue(t.getProjectCost().toString());
			userlistFt.clear();
			inviteTb.setEnabled(true);
			inviteButton.setEnabled(true);
			int row = 0;
			delButton.clear();
			for(String u : t.getRelatedUsernames()) {
				final Button bt = new Button(u);
				bt.addClickHandler(new ClickHandler() {
					@Override
					public void onClick(ClickEvent event) {
						final Listener<MessageBoxEvent> l = new Listener<MessageBoxEvent>() {  
						      public void handleEvent(MessageBoxEvent ce) {  
						        if(ce.getButtonClicked().getText().equals("Yes")) {
						        	t.delRelatedUsername(bt.getText());
						        	tagService.rejectShare(t.getId(), bt.getText(), new AsyncCallback() {
			                    		 public void onFailure(Throwable caught) {
							                    GWT.log("Failed to check the Validity of Username, Exception thrown", caught);
							                }

							                public void onSuccess(Object result) {
							                	update();
							                	GWT.log("Tag updated!", null);
							                }
			                    	});
						        } 
						      }  
						    };  
						MessageBox.confirm("Confirm", "Wollen Sie die Freigabe von diesem Benutzer ablehnen?", l);
					}
				});
				delButton.add(bt);
				userlistFt.setWidget(row++, 0, bt);
			}
		} else {
			disableDetails();
		}
	}
	
	public HasClickHandlers getInviteClickHandlers() {
		return inviteButton;
	}
	
	public HasValue<String> getInvite() {
		return inviteTb;
	}
	
	public HasValue<String> getTag() {
		return tagTb;
	}
}
